package com.ken.teacher.service.serviceImpl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import com.ken.common.pojo.*;
import com.ken.common.pojo.Class;
import com.ken.common.result.Result;
import com.ken.common.utils.OssUtil;
import com.ken.common.utils.QRUtil;
import com.ken.common.utils.imgUtil;
import com.ken.teacher.dto.*;
import com.ken.teacher.mapper.teacherMapper;
import com.ken.teacher.service.teacherService;
import com.ken.teacher.vo.attendanceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.File;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class teacherServiceImpl implements teacherService {
    @Autowired
    private teacherMapper teacherMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private TaskScheduler taskScheduler;
    @Override
    public Result<Class> createClass(createClassDto dto) throws Exception {
        //创建随机班级id
        String class_id = RandomUtil.randomString("numericLetter", 6);
        //利用利用班级id生成班级码
        String qr = QRUtil.createQR(class_id);
        //设置基础属性
        Class Class = new Class(class_id,dto.getId(),0,qr,dto.getClass_name(),dto.getCourse_id());
        //将生成班级信息存入数据库
        teacherMapper.createClass(Class);
        return Result.success(Class);
    }

//    @Override
//    public Result<String> saveInformation(List<noSignInDto> noSignIn) {
//        //检查数组是否为空
//        if(ArrayUtil.isEmpty(noSignIn)) return Result.success("保存成功");
//        //若不为空则保存考勤信息
//        LocalDate now = LocalDate.now();
//        LocalDateTime nowDateTime = LocalDateTime.now();
//        for(noSignInDto dto:noSignIn){
//            dto.setDate(now);
//            dto.setCreated_at(nowDateTime);
//            dto.setUpdated_at(nowDateTime);
//            teacherMapper.saveAttendance(dto);
//        }
//        return Result.success("保存成功");
//    }

    @Override
    public Result<String> createQuestion(Question question) {
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        question.setCreated_at(LocalDateTime.now());
        question.setUpdated_at(LocalDateTime.now());
        question.setId(id);
        teacherMapper.CreateQuestion(question);
        return Result.success(id);
    }

    @Override
    public Result<String> create_homework(homeworkDto homework) {
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        homework.setId(id);
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        homework.setUpdate_time(now);
        teacherMapper.create_homework(homework);
        return Result.success(id);
    }

    @Override
    public Result<String> post_homework(post_homeworkDto dto) {
        //获取作业详情
        homework homework = teacherMapper.getHomeworkById(dto.getHomework_id());
        //根据班级号获取班级学生情况
        List<student> classStudents = teacherMapper.getClassStudent(dto.getClass_id());
        //获取发布时间
        LocalDateTime now = LocalDateTime.now();
        dto.setAssignment_date(now);
        //班级发布情况
        teacherMapper.post_homeworkToClass(dto);
        //为每个学生都发布作业情况
        for(student student:classStudents){
            teacherMapper.post_homework(student.getStudent_id(),dto.getHomework_id(),now,dto.getDue_date());
        }
        return Result.success("发布成功");
    }

    @Override
    public Result<String> add_question(add_questionDto dto) {
        //更新时间
        teacherMapper.update_homeworkTime(LocalDateTime.now());
        //将绑定信息写入数据库
        teacherMapper.add_question(dto);
        //将试卷的题数加一
        teacherMapper.change_pageQ_num();
        return Result.success("添加成功");
    }

    @Override
    public Result<String> create_paper(paper paper) {
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        paper.setPaper_id(id);
        teacherMapper.create_paper(paper);
        return Result.success(id);
    }

    @Override
    public Result<String> add_paperQuestion(add_paperQuestionDto questionDto) {
        log.info(questionDto.toString());
        teacherMapper.add_paperQuestion(questionDto);
        return Result.success("添加成功");
    }

    @Override
    public Result<String> post_exam(examDto examDto) {
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        //创建考试
        LocalDateTime now = LocalDateTime.now();
        exam exam = new exam(id,examDto.getPaper_id(),examDto.getClass_id(),now,examDto.getDue_date(),examDto.getStatus());
        teacherMapper.create_exam(exam);
        //利用class_id获取班级所有学生
        List<student> classStudent = teacherMapper.getClassStudent(examDto.getClass_id());
        for(student student:classStudent){
            //将考试信息发布到每个学生
            teacherMapper.post_exam(student.getStudent_id(),id);
        }
        return Result.success(id);
    }

    @Override
    public void change_status(change_statusDto dto) {
        //判断要更改的是作业还是考试的状态
        if(dto.getType().equals("exam")){
            teacherMapper.change_homeworkStatus(dto);
        }else {
            teacherMapper.change_examStatus(dto);
        }
    }

    @Override
    public void grade_assignments(grade_assignmentDto assignmentDto) {
        //将目前批改的得分更新到学生的作业情况中
        teacherMapper.change_studentHomework(assignmentDto.getStudent_id(),assignmentDto.getHomework_id(),assignmentDto.getScore());
        //将批改情况更新到数据库
        teacherMapper.grade_assignments(assignmentDto);
    }

    @Override
    public String create_unit(unitDto dto) {

            String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
            dto.setUnit_id(id);
            teacherMapper.create_unit(dto);

        return id;
    }

//    @Override
//    public String create_lesson(create_lessonDto dto) {
//        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
//        dto.setLesson_id(id);
//        teacherMapper.create_lesson(dto);
//        return id;
//    }

    @Override
    public String create_course(create_courseDto dto) throws Exception {
        //随机生成课程id
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        dto.setCourse_id(id);
        //讲封面上传oss
        String img_code=dto.getImg_base64().split(",",2)[1];
        File file = imgUtil.Base64ToFileUtil(img_code, dto.getImg_end());
        UUID uuid = UUID.randomUUID();
        String url = OssUtil.upload(file, uuid.toString());
        dto.setCover(url);
        teacherMapper.create_course(dto);
        return id;
    }

    @Override
    public List<course> getCourseByTeacherId(String teacher_id) {
        List<course> courses = teacherMapper.getCourseByTeacherId(teacher_id);
        for(course course:courses){
            course.setSchool(teacherMapper.getInfById(teacher_id).getSchool());
        }
        return courses;
    }

    @Override
    public List<String> create_questions(List<Question> questions) {
        ArrayList<String> ids = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (Question question:questions){
            String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
            question.setId(id);
            question.setCreated_at(now);
            question.setUpdated_at(now);
            ids.add(id);
            teacherMapper.CreateQuestion(question);
        }
        return ids;
    }

    @Override
    public void update_question(update_questionDto dto) {
        //获取更新时间
        LocalDateTime now = LocalDateTime.now();
        Timestamp timestamp = Timestamp.valueOf(now);
        dto.setUpdated_at(timestamp);
        //修改进数据库
        teacherMapper.update_question(dto);
    }

    @Override
    public void post_message(message message) {
        //先将消息存入数据库
        //生成一个id
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        message.setMessage_id(id);
        teacherMapper.save_message(message);
        //将消息发送到班上所有学生
        List<student> classStudents = teacherMapper.getClassStudent(message.getClass_id());
        for (student student:classStudents){
            teacherMapper.post_message(student.getStudent_id(),id);
        }
    }

    @Override
    public attendanceVo post_attendance(attendanceDto dto) throws Exception {
        String code = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        //获取班级所有的学生
        List<student> classStudents = teacherMapper.getClassStudent(dto.getClass_id());
        //给每个学生发送一个通知
        message message = new message();
        String id = RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        message.setMessage_id(id);
        message.setType("签到");
        message.setPost_time(LocalDateTime.now());
        message.setClass_id(dto.getClass_id());
        message.setTitle("签到");
        message.setContent(code);
        message.setSender(teacherMapper.getInfById(dto.getTeacher()).getName());
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endTime = now.plusSeconds(dto.getTime());
        message.setEnd_time(endTime);
        teacherMapper.save_message(message);
        for(student student :classStudents){
            teacherMapper.post_message(student.getStudent_id(),id);
        }
        //设置返回数据
        attendanceVo attendanceVo = new attendanceVo();
        ArrayList<attendance> attendances = new ArrayList<>();
        //生成签到码并上传

        String url = QRUtil.createQR(code);
        long student_num=0;
        //将考勤信息放入redis中
        for(student student :classStudents){
            attendance attendance = new attendance();
            attendance.setClass_id(dto.getClass_id());
            attendance.setState("未签到");
            attendance.setStudent_id(student.getStudent_id());
            attendance.setStudent_name(student.getName());
            attendances.add(attendance);
            attendance_record attendanceRecord = new attendance_record(student.getStudent_id(),dto.getClass_id(),LocalDateTime.now(),"未签到",student.getName(),code);
            teacherMapper.save_attendanceRecord(attendanceRecord);
            student_num++;
            String key=dto.getClass_id()+"-"+student.getStudent_id()+"-"+code;
            redisTemplate.opsForValue().set(key,"未签到",dto.getTime(), TimeUnit.SECONDS);
        }
        attendanceVo.setAttendanceVos(attendances);
        attendanceVo.setStudent_num(student_num);
        attendanceVo.setUrl(url);
        attendanceVo.setCode(code);
        //设置定时任务
        taskScheduler.schedule(() -> {
            log.info("开始更新数据");
            // 在延迟时间后执行的任务逻辑，例如保存数据到数据库
            for(student student:classStudents){
                String key=dto.getClass_id()+"-"+student.getStudent_id()+"-"+code;
                String type = redisTemplate.opsForValue().get(key);
                attendance_record attendanceRecord = new attendance_record(student.getStudent_id(),dto.getClass_id(),LocalDateTime.now(),type,student.getName(),code);
                if (type.equals("已签到")){
                    attendanceRecord.setType("出勤");
                }else {
                    attendanceRecord.setType("缺勤");
                }
                teacherMapper.update_attendanceRecord(attendanceRecord);
            }
        }, new Date(System.currentTimeMillis() + (dto.getTime() * 1000-500))); // 将秒转换为毫秒

        return attendanceVo;
    }

    @Override
    public void  create_lessons(lessons lessons) {
        teacherMapper.create_lesson(lessons);
    }

    @Override
    public void update_lesson(lessons lesson) {
        teacherMapper.update_lesson(lesson);
    }

    @Override
    public void update_unit(unit unit) {
        teacherMapper.update_unit(unit);
    }

    @Override
    public void delete_lesson(String lesson_id) {
        teacherMapper.delete_lesson(lesson_id);
    }

    @Override
    public void delete_unit(String unit_id) {
        teacherMapper.delete_unit(unit_id);
    }

    @Override
    public String create_courseware(courseware courseware) {
        //生成id
        String id=RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        courseware.setCourseware_id(id);
        courseware.setUpdateTime(LocalDateTime.now());
        teacherMapper.create_courseware(courseware);
        return id;
    }

    @Override
    public void update_courseware(courseware courseware) {
        courseware.setUpdateTime(LocalDateTime.now());
        log.info(courseware.getUpdateTime().toString());
        teacherMapper.update_courseware(courseware);
    }

    @Override
    public List<courseware> getCourseware(String teacher_id, String courseware_id,String course_id) {
        List<courseware> coursewares = teacherMapper.getCourseware(teacher_id, courseware_id,course_id);
        return coursewares;
    }

    @Override
    public String post_resources(resources resources) {
        String id=RandomUtil.randomString(RandomUtil.BASE_CHAR_NUMBER, 6);
        resources.setResources_id(id);
        resources.setPost_date(LocalDateTime.now());
        teacherMapper.post_resources(resources);
        return id;
    }

    @Override
    public List<resources> get_resources(String class_id, String resources_id) {

        return teacherMapper.get_resources(class_id,resources_id);
    }


}
